package com.caigou.modules.forum.ui.forum

import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.hideKeyboard
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.forum.R
import com.caigou.modules.forum.adpter.ForumItemAdapter
import com.caigou.modules.forum.adpter.UserItemAdapter
import com.caigou.modules.forum.bean.PostBean
import com.caigou.modules.forum.bean.SearchUserBean
import com.caigou.modules.forum.databinding.ActivitySearchBinding
import com.caigou.modules.forum.viewmodel.SearchViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2022/02/12
 */
@Route(path = RouterPath.Forum.PAGE_FORUM_SEARCH)
@AndroidEntryPoint
class ForumSearchActivity : BaseActivity() {

    private lateinit var binding: ActivitySearchBinding
    private val searchViewModel: SearchViewModel by viewModels()

    private var page = 1
    private val limit = 10
    private var totalPage = 0

    @JvmField
    @Autowired(name = AppConstants.FORUM_TYPE)
    var forumType = 1

    private var contentType = 2

    private val userAdapter: UserItemAdapter by lazy {
        UserItemAdapter(mutableListOf())
    }

    private val postAdapter: ForumItemAdapter by lazy {
        ForumItemAdapter(mutableListOf())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivitySearchBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.searchLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)

        with(binding.searchEetContent) {
            leftImageView.visibility = View.VISIBLE
            leftImageView.setImageResource(R.drawable.img_forum_search_gray)
            editText.imeOptions = EditorInfo.IME_ACTION_SEARCH
            editText.inputType = EditorInfo.TYPE_CLASS_TEXT
            editText.setOnEditorActionListener(object : TextView.OnEditorActionListener {
                override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                    if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER)) {
                        hideKeyboard()
                        search()
                        return true
                    }
                    return false
                }

            })
        }

        userAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                userAdapter.loadMoreModule.isEnableLoadMore = true
                search()
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }
        binding.searchUserRecyclerView.run {
            layoutManager = LinearLayoutManager(this@ForumSearchActivity)
            adapter = userAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@ForumSearchActivity))
        }
        userAdapter.setOnItemClickListener { _, _, position ->
            val item = userAdapter.getItem(position)
            ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                .withString(AppConstants.USER_ID, item.userId)
                .navigation()
        }

        postAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                postAdapter.loadMoreModule.isEnableLoadMore = true
                search()
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }
        binding.searchPostRecyclerView.run {
            layoutManager = LinearLayoutManager(this@ForumSearchActivity)
            adapter = postAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@ForumSearchActivity))
        }
        postAdapter.setOnItemClickListener { _, _, position ->
            val item = postAdapter.getItem(position)
            ARouter.getInstance().build(RouterPath.Forum.PAGE_FORUM_POST)
                .withInt(AppConstants.POST_ID, item.id)
                .navigation()
        }

        binding.searchRgSelector.setOnCheckedChangeListener { group, checkedId ->
            when (group.checkedRadioButtonId) {
                binding.searchBtnPost.id -> {
                    contentType = 1
                    binding.searchPostRecyclerView.visibility = View.VISIBLE
                    binding.searchUserRecyclerView.visibility = View.GONE
                }
                binding.searchBtnUser.id -> {
                    contentType = 2
                    binding.searchPostRecyclerView.visibility = View.GONE
                    binding.searchUserRecyclerView.visibility = View.VISIBLE
                }
            }
            search()
        }

        binding.searchTvBack.setOnClickListener {
            finish()
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(searchViewModel.searchUserLiveData, ::handleSearchUser)
        observe(searchViewModel.searchPostLiveData, ::handleSearchPost)
    }

    private fun handleSearchUser(result: Resource<SearchUserBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取用户信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                totalPage = result.data!!.totalPage

                if (page == 1) {
                    userAdapter.setList(result.data!!.list)
                } else {
                    userAdapter.addData(result.data!!.list)
                }

                if (result.data!!.pageSize < limit) {
                    userAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    userAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    userAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
            }
        }
    }

    private fun handleSearchPost(result: Resource<PostBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取帖子信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                totalPage = result.data!!.totalPage

                if (page == 1) {
                    postAdapter.setList(result.data!!.list)
                } else {
                    postAdapter.addData(result.data!!.list)
                }

                if (result.data!!.pageSize < limit) {
                    postAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    postAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    postAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
            }
        }
    }

    private fun search() {
        val text = binding.searchEetContent.editText.text.toString()
        if (TextUtils.isEmpty(text)) {
            return
        }
        page = 1
        if (contentType == 1) {
            searchViewModel.searchPost(limit, page, forumType, text)
        } else {
            searchViewModel.searchUser(limit, page, forumType, text)
        }
    }
}